const { DataTypes } = require("sequelize");
const { sequelize } = require("../config/database");

const UserAiConversation = sequelize.define(
  "UserAiConversation",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
      comment: "主键ID",
    },
    user_uuid: {
      type: DataTypes.CHAR(36),
      allowNull: false,
      comment: "用户UUID",
    },
    ai_person_id: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: "AI角色ID",
    },
    ai_avatar: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: "AI角色头像URL",
    },

    // 核心对话数据 - JSON格式，快速加载
    conversation_data: {
      type: DataTypes.JSON,
      allowNull: false,
      defaultValue: {
        messages: [],
        metadata: {
          total_messages: 0,
          first_message_time: null,
          last_message_time: null,
          ai_name: "",
          avatar_url: "",
        },
      },
      comment: "完整对话数据（JSON格式）",
    },

    // 冗余字段 - 便于查询和索引
    total_messages: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "消息总数",
    },
    last_message_content: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: "最后一条消息内容（便于预览）",
    },
    last_message_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: "最后一条消息时间",
    },
    last_sender: {
      type: DataTypes.ENUM("user", "ai"),
      allowNull: true,
      comment: "最后发送者",
    },

    // 状态和配置
    is_active: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true,
      comment: "对话是否活跃",
    },
    conversation_title: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "对话标题（可自定义）",
    },

    // 统计信息
    user_message_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "用户消息数量",
    },
    ai_message_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "AI消息数量",
    },

    // 性能优化字段
    data_size_bytes: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "JSON数据大小（字节）",
    },
    last_accessed_at: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: "最后访问时间",
    },
    // 新增字段：未读消息数
    last_message_status: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "未读消息数",
    },
  },
  {
    tableName: "user_ai_conversations",
    timestamps: true,
    comment: "用户与AI的对话记录表",

    indexes: [
      // 主要查询索引
      {
        unique: true,
        fields: ["user_uuid", "ai_person_id"],
        name: "idx_user_ai_unique",
      },
      // 活跃对话查询
      {
        fields: ["user_uuid", "is_active", "last_message_time"],
        name: "idx_user_active_conversations",
      },
      // 最近对话查询
      {
        fields: ["last_message_time"],
        name: "idx_recent_conversations",
      },
      // AI角色统计
      {
        fields: ["ai_person_id", "is_active"],
        name: "idx_ai_conversations",
      },
      // 数据大小监控
      {
        fields: ["data_size_bytes"],
        name: "idx_data_size",
      },
    ],

    hooks: {
      // 更新前自动计算数据大小
      beforeUpdate: (instance) => {
        if (instance.changed("conversation_data")) {
          const dataStr = JSON.stringify(instance.conversation_data);
          instance.data_size_bytes = Buffer.byteLength(dataStr, "utf8");

          // 更新统计信息
          const messages = instance.conversation_data.messages || [];
          instance.total_messages = messages.length;
          instance.user_message_count = messages.filter(
            (m) => m.sender === "user"
          ).length;
          instance.ai_message_count = messages.filter(
            (m) => m.sender === "ai"
          ).length;

          if (messages.length > 0) {
            const lastMessage = messages[messages.length - 1];
            instance.last_message_content =
              lastMessage.content?.substring(0, 500) || "";
            instance.last_message_time = new Date(lastMessage.timestamp);
            instance.last_sender = lastMessage.sender;
          }
          
          // 同步头像信息到独立字段
          if (instance.conversation_data.metadata?.avatar_url) {
            instance.ai_avatar = instance.conversation_data.metadata.avatar_url;
          }
        }

        instance.last_accessed_at = new Date();
      },

      beforeCreate: (instance) => {
        const dataStr = JSON.stringify(instance.conversation_data);
        instance.data_size_bytes = Buffer.byteLength(dataStr, "utf8");
        instance.last_accessed_at = new Date();
        
        // 同步头像信息到独立字段
        if (instance.conversation_data.metadata?.avatar_url) {
          instance.ai_avatar = instance.conversation_data.metadata.avatar_url;
        }
      },
    },
  }
);

// 实例方法
UserAiConversation.prototype.addMessage = function (messageData) {
  const messages = this.conversation_data.messages || [];

  // 添加新消息
  messages.push({
    id:
      messageData.id ||
      `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
    type: messageData.type || "text",
    content: messageData.content,
    sender: messageData.sender,
    timestamp: messageData.timestamp || Date.now(),
    status: messageData.status || "completed",
    extra_data: messageData.extra_data || null,
  });

  // 更新对话数据
  this.conversation_data = {
    ...this.conversation_data,
    messages: messages,
    metadata: {
      ...this.conversation_data.metadata,
      total_messages: messages.length,
      last_message_time: messages[messages.length - 1].timestamp,
      first_message_time:
        this.conversation_data.metadata.first_message_time ||
        messages[0].timestamp,
    },
  };

  return this;
};

// 获取最近N条消息
UserAiConversation.prototype.getRecentMessages = function (limit = 50) {
  const messages = this.conversation_data.messages || [];
  return messages.slice(-limit);
};

// 搜索消息
UserAiConversation.prototype.searchMessages = function (keyword) {
  const messages = this.conversation_data.messages || [];
  return messages.filter(
    (msg) =>
      msg.content && msg.content.toLowerCase().includes(keyword.toLowerCase())
  );
};

// 类方法
UserAiConversation.findOrCreateConversation = async function (
  userUuid,
  aiPersonId,
  aiData = {}
) {
  const [conversation, created] = await UserAiConversation.findOrCreate({
    where: {
      user_uuid: userUuid,
      ai_person_id: aiPersonId,
    },
    defaults: {
      ai_avatar: aiData.avatar || "",
      conversation_data: {
        messages: [],
        metadata: {
          total_messages: 0,
          first_message_time: null,
          last_message_time: null,
          ai_name: aiData.name || "",
          avatar_url: aiData.avatar || "",
        },
      },
    },
  });

  return { conversation, created };
};

module.exports = UserAiConversation;
